import request from '@/utils/request';
import type { Order, OrderListData, OrderQuery, OrderStatus } from '@/types/order';

/**
 * 获取订单列表
 * @param params 查询参数
 * @returns 订单列表数据
 */
export const fetchOrders = (params: OrderQuery) => {
  return request<OrderListData>({
    url: '/v1/order',
    method: 'GET',
    data: params,
  });
};

/**
 * 获取订单详情
 * @param id 订单ID
 * @returns 订单详情
 */
export const fetchOrderDetail = (id: number) => {
  return request<Order>({
    url: `/v1/order/${id}`,
    method: 'GET',
  });
};

/**
 * 更新订单状态
 * @param id 订单ID
 * @param status 订单状态
 * @param remark 备注
 * @returns 更新结果
 */
export const updateOrderStatus = (id: number, status: number, remark?: string) => {
  return request<any>({
    url: '/v1/order/status',
    method: 'POST',
    data: { id, status, remark },
  });
};

/**
 * 代客下单
 * @param data 订单数据
 * @returns 创建的订单
 */
export const createOrderByAdmin = (data: any) => {
  return request<Order>({
    url: '/v1/order/create_by_admin',
    method: 'POST',
    data,
  });
};

/**
 * 更换场地
 * @param orderId 订单ID
 * @param newVenueId 新场地ID
 * @returns 更新后的订单
 */
export const rescheduleOrder = (orderId: number, newVenueId: number) => {
  return request<Order>({
    url: `/v1/order/${orderId}/reschedule`,
    method: 'PUT',
    data: { venue_id: newVenueId },
  });
};

/**
 * 批量更新订单状态
 * @param orderIds 订单ID列表
 * @param status 目标状态
 * @param remark 备注
 * @returns 批量更新结果
 */
export const batchUpdateOrderStatus = (orderIds: number[], status: OrderStatus, remark?: string) => {
  return request<{ success_count: number; failed_count: number; failed_orders: number[] }>({
    url: '/v1/order/batch/status',
    method: 'PUT',
    data: {
      order_ids: orderIds,
      status,
      remark,
    },
  });
};

/**
 * 批量导出订单
 * @param orderIds 订单ID列表
 * @param format 导出格式 (excel, csv, pdf)
 * @returns 导出结果
 */
export const batchExportOrders = (orderIds: number[], format: 'excel' | 'csv' | 'pdf' = 'excel') => {
  return request<{ download_url: string; file_name: string }>({
    url: '/v1/order/batch/export',
    method: 'POST',
    data: {
      order_ids: orderIds,
      format,
    },
  });
};

/**
 * 获取订单操作历史
 * @param orderId 订单ID
 * @returns 操作历史列表
 */
export const fetchOrderHistory = (orderId: number) => {
  return request<Array<{
    id: number;
    action: string;
    remark?: string;
    operator?: string;
    created_at: number;
  }>>({
    url: `/v1/order/${orderId}/history`,
    method: 'GET',
  });
};

/**
 * 获取订单统计数据
 * @param params 查询参数
 * @returns 统计数据
 */
export const fetchOrderStatistics = (params?: {
  store_id?: number;
  start_date?: string;
  end_date?: string;
  start_time?: number;
  end_time?: number;
}) => {
  return request<{
    total_orders: number;
    pending_orders: number;
    today_orders: number;
    total_amount: number;
    completed_orders: number;
    cancelled_orders: number;
  }>({
    url: '/v1/order/statistics',
    method: 'GET',
    data: params,
  });
};

/**
 * 代客下单
 * @param orderData 订单数据
 * @returns 创建的订单
 */
export const createOrderForCustomer = (orderData: {
  member_id: number;
  store_id: number;
  venue_id: number;
  start_time: number;
  end_time: number;
  remark?: string;
  payment_method?: string;
}) => {
  return request<Order>({
    url: '/v1/order/create-for-customer',
    method: 'POST',
    data: orderData,
  });
};

/**
 * 检查时间段可用性
 * @param params 检查参数
 * @returns 可用性检查结果
 */
export const checkTimeSlotAvailability = (params: {
  venue_id: number;
  start_time: number;
  end_time: number;
  exclude_order_id?: number;
}) => {
  return request<{
    available: boolean;
    conflicting_orders?: Array<{
      id: number;
      order_no: string;
      start_time: number;
      end_time: number;
    }>;
  }>({
    url: '/v1/order/check-availability',
    method: 'POST',
    data: params,
  });
};

/**
 * 获取门店列表
 * @returns 门店列表
 */
export const fetchStoreList = () => {
  return request<Array<{
    id: number;
    name: string;
    address?: string;
    status?: number;
  }>>({
    url: '/v1/store',
    method: 'GET',
  });
};

/**
 * 获取导出订单记录的URL
 * @param params 查询参数
 * @returns 导出URL
 */
export const getExportOrdersUrl = (params: Record<string, any>): string => {
  const baseUrl = process.env.VUE_APP_BASE_API || '';
  let exportUrl = `${baseUrl}/v1/order/export?`;
  
  Object.keys(params).forEach(key => {
    if (params[key] !== undefined && params[key] !== null) {
      exportUrl += `${key}=${encodeURIComponent(params[key])}&`;
    }
  });
  
  // 移除最后的 &
  return exportUrl.slice(0, -1);
};

// 兼容性导出 - 保持与JS版本的兼容性
export {
  fetchOrders as fetchOrderRecords,
  fetchOrderDetail as fetchOrderRecordDetail,
  fetchOrderStatistics as getOrderStatistics,
  fetchStoreList as getStoreList,
  getExportOrdersUrl as getExportUrl
};